package com.competition.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.competition.dao.WxInfo;
import com.competition.dao.WxUserInfo;
import com.competition.entity.User;
import com.competition.resp.ResponseResult;
import com.competition.service.UserService;
import com.competition.utils.http.HttpClientUtil;
import com.competition.utils.jwt.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
@Slf4j
public class LoginController {
    @Autowired
    private WxInfo wxInfo;

    @Autowired
    private UserService userService;

    @PostMapping("/onLogin")
    public ResponseResult Login(@RequestBody Map<String, Object> params) {
        if (params.get("userInfo") == null) {
            return new ResponseResult(300, "空值", null);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        WxUserInfo userInfo = objectMapper.convertValue(params.get("userInfo"), WxUserInfo.class);
        if (params.get("code") == null) {
            return new ResponseResult(300, "空值", null);
        }
        // 配置请求参数 获取openid
        Map<String, String> param = new HashMap<>();
        param.put("appid", wxInfo.getAPPID());
        param.put("secret", wxInfo.getAPPSECRET());
        param.put("js_code", (String) params.get("code"));

        String wxResult = HttpClientUtil.doGet(wxInfo.getURL(), param);


        JSONObject json = JSONObject.parseObject(wxResult);
        System.out.println("json--"+json);
        if (json == null) {
            return new ResponseResult(300, "登录失败", null);
        }
        String open_id = json.get("openid").toString();
        String session_key = json.get("session_key").toString();
        //设置返回的参数
        Map<String, String> result = new HashMap<>();
        result.put("session_key", session_key);
        result.put("open_id", open_id);
        result.put("avatarUrl", userInfo.getAvatarUrl());
        result.put("nickName", userInfo.getNickName());


        //根据openid判断user库是否存在用户 没就注册
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", open_id);
        User byId = userService.getOne(wrapper);
        //设置JWT令牌
        Map<String, String> payload = new HashMap<>();
        payload.put("open_id", open_id);
        payload.put("session_key", session_key);
        String token = JWTUtils.getToken(payload);
        result.put("state", "true");
        result.put("token", token);
        if (byId == null) {
            //登录并先注册一部分信息
            result.put("zhuce", "888");
            userService.save(new User(open_id, userInfo.getNickName(), null, null,userInfo.getAvatarUrl(),new Date(), null));
            return new ResponseResult(200, "登录没注册", result);
        }

        return new ResponseResult(200, "登录成功", result);//result 要传 token
    }

    @PostMapping("/onRegister")
    public ResponseResult register(@RequestBody Map<String, Object> params) {
        String username = (String) params.get("username");
        String sex = (String) params.get("sex");
        String idcard = (String) params.get("idcard");
        String phoneNumber = (String) params.get("phoneNumber");
        String openId = (String) params.get("openId");
        try{
            User user = new User();
            user.setUserIdcare(idcard);
            user.setUserPhone(phoneNumber);
            user.setUserName(username);
            user.setUserSex(sex);
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", openId);
            boolean update = userService.update(user, updateWrapper);
            if (update){
                return new ResponseResult(200, "注册成功", null);//null 要传 token
            }else {
                return new ResponseResult(300, "注册失败", null);//null 要传 token
            }
        }catch (Exception e){
            return new ResponseResult(300, "注册失败", null);//null 要传 token
        }



    }
}
